package com.cadre.web.controller.officer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cadre.common.exception.CadreException;
import com.cadre.common.exception.RRException;
import com.cadre.common.utils.R;
import com.cadre.common.utils.SecurityUtils;
import com.cadre.common.utils.ZipUtil;
import com.cadre.common.utils.annotation.A01Tag;
import com.cadre.common.utils.annotation.SysLog;
import com.cadre.common.utils.common.GenerateUUID;
import com.cadre.common.utils.common.HttpContextUtils;
import com.cadre.common.utils.common.RealUrlUtil;
import com.cadre.common.utils.oldutil.*;
import com.cadre.system.domain.officer.*;
import com.cadre.system.domain.vo.ESUtil;
import com.cadre.system.olddomain.XMLUtils;
import com.cadre.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.dom4j.DocumentException;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.security.NoSuchAlgorithmException;
import java.sql.Blob;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Api(tags = {"人员接口"})
@RequestMapping({"/profess/a01"})
@RestController
public class A01Controller {
    @Resource
    private A01Service a01Service;
    @Resource
    private A22Service a22Service;
    @Resource
    private A26Service a26Service;
    @Resource
    private A16Service a16Service;
    @Resource
    private A79Service a79Service;
    @Resource
    private A04Service a04Service;
    @Resource
    private B01Service b01Service;
    @Resource
    private A19Service a19Service;
    @Resource
    private SysLogService sysLogService;
    @Autowired
    RestHighLevelClient client;
    @Autowired
    TreeService treeSer;
    @Autowired
    private AppointRemoveService appointRemoveService;
    @Value("${record-system-url}")
    private String recordsystemurl;
    @Autowired
    private A04Controller a04Controller;
    static int flag = 1;

    @GetMapping({"/info/{flowId}"})
    @ApiOperation("详情")
    public R info(@PathVariable("flowId") String flowId) {
        A01 a01 = (A01) this.a01Service.getById(flowId);
        System.out.println(a01.getA0138() + ">>>>>>>>>>>>>>>>>>>>>>");
        int age = 0;
        if (a01.getA0106() != null) {
            age = AgeUtil.getCurrentAge(a01.getA0106());
        }
        return R.ok().put("a01", (Object) a01).put("age", (Object) Integer.valueOf(age));
    }

    @GetMapping({"/schoolAndMajor"})
    @ApiOperation("学校及专业接口(全日制)")
    public R schoolAndMajor() {
        LambdaQueryWrapper lambdaQueryWrapper = Wrappers.<A01>lambdaQuery().apply("DISTINCT a0188").isNotNull(A01::getA0188);
        return R.ok().put("data", (Object) this.a01Service.getBaseMapper().selectList(lambdaQueryWrapper));
    }

    @GetMapping({"/schoolAndMajorT"})
    @ApiOperation("学校及专业接口(在职)")
    public R schoolAndMajorT() {
        LambdaQueryWrapper lambdaQueryWrapper = Wrappers.<A01>lambdaQuery().apply("DISTINCT a0191").isNotNull(A01::getA0191);
        return R.ok().put("data", (Object) this.a01Service.getBaseMapper().selectList(lambdaQueryWrapper));
    }

    @GetMapping({"/education"})
    @ApiOperation("学历字典(全日制)")
    public R education() {
        LambdaQueryWrapper lambdaQueryWrapper = Wrappers.<A01>lambdaQuery().apply("DISTINCT a0187").isNotNull(A01::getA0187);
        return R.ok().put("data", (Object) this.a01Service.getBaseMapper().selectList(lambdaQueryWrapper));
    }

    @GetMapping({"/educationT"})
    @ApiOperation("学历字典(在职)")
    public R educationT() {
        LambdaQueryWrapper lambdaQueryWrapper = Wrappers.<A01>lambdaQuery().apply("DISTINCT a0190").isNotNull(A01::getA0190);
        return R.ok().put("data", (Object) this.a01Service.getBaseMapper().selectList(lambdaQueryWrapper));
    }

    @GetMapping({"/nativePlace"})
    @ApiOperation("籍贯字典")
    public R nativePlace() {
        LambdaQueryWrapper lambdaQueryWrapper = Wrappers.<A01>lambdaQuery().apply("DISTINCT a0108").isNotNull(A01::getA0108);
        return R.ok().put("data", (Object) this.a01Service.getBaseMapper().selectList(lambdaQueryWrapper));
    }

    @PostMapping({"selectList"})
    @ApiOperation("批量查询")
    public R selectList(@RequestBody List<String> idList) {
        return R.ok().put("data", (Object) this.a01Service.getBaseMapper().selectBatchIds(idList));
    }

    @PostMapping({"/save"})
    @A01Tag("更新")
    @SysLog(value = "新增人员基本信息", target = "A01", set = "A01", type = 0)
    @ApiOperation("增")
    public R save(@RequestBody A01 a01) {
        System.out.println("保存A01信息Controller方法");
        String att = GenerateUUID.getUUID();
        a01.setFlowid(att);
        a01.setA0102(PinYinUtil.getPingYin(a01.getA0101()).toUpperCase() + "," + PinYinUtil.getFirstSpell(a01.getA0101()).toUpperCase());
        if (Integer.valueOf(this.a01Service.checkA01Repeat(a01)).intValue() > 0) {
            return R.error("已存在姓名 性别 出生年月相同的数据！");
        }
        this.a01Service.insertSelective(a01);
        if (a01.getA0201() == null || "2".equals(a01.getA0201())) {
        }
        return R.ok().put("flowid", (Object) att).put("a0101", (Object) a01.getA0101());
    }

    @PostMapping({"/uploadLrmxFile"})
    @ApiOperation(value = "上传单个lrmx文件", notes = "file:单文件,返回结果:a01")
    public R uploadLrmxFile(@RequestBody MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws DocumentException {
        String s;
        new FileUtils();
        FileUtils.isOSlinux();
        String basePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "/temp/lrmx/" + SecurityUtils.getUserId();
        File baseDir = new File(basePath);
        if (!baseDir.exists()) {
            baseDir.mkdirs();
        }
        System.out.println("basePath1:" + basePath);
        new XMLUtils();
        File comonfile = new File(basePath + ("lrmx_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + XMLUtils.randomHexString(5) + ".lrmx"));
        try {
            file.transferTo(comonfile);
        } catch (Exception e) {
            System.out.println("UploadLrmxFile error:" + e.getMessage());
        }
        new A01();
        try {
            A01 a01 = XMLUtils.getA01ByLrmxFile(comonfile);
            String a0171string = a01.getA0171string();
            if (!StringUtils.isEmpty(a0171string)) {
                a01.setA0171(Base64.decodeBase64(a0171string.replace("zhaopian str:", "")));
            } else {
                String a0105 = a01.getA0105();
                if (!StringUtils.isEmpty(a0105)) {
                    if ("女".equals(a0105)) {
                        s = RealUrlUtil.getRootUrl() + "\\cadre-system\\src\\resources\\pic\\nv_pic.jpg";
                    } else {
                        s = RealUrlUtil.getRootUrl() + "\\cadre-system\\src\\resources\\pic\\nan_pic.jpg";
                    }
                    File files = new File(s);
                    if (files.exists()) {
                        a01.setA0171(file2Byte(files));
                    }
                }
            }
            a01.setA0181("在职干部");
            comonfile.delete();
            if (Integer.valueOf(this.a01Service.checkA01Repeat(a01)).intValue() > 0) {
                a01.setRepeatFlag(1);
            } else {
                a01.setRepeatFlag(0);
            }
            System.out.println(comonfile.exists());
            return R.ok().put("a01", (Object) a01);
        } catch (Exception ex) {
            ex.printStackTrace();
            comonfile.delete();
            return R.error();
        }
    }

    @PostMapping({"/uploadCadreFile"})
    @ApiOperation(value = "上传单个lrmx或zip文件", notes = "file:单文件,返回结果:res")
    public R uploadCadreFile(@RequestBody MultipartFile file, @RequestParam String[] ids, HttpServletRequest request, HttpServletResponse response) throws DocumentException {
        System.out.println("ids:" + ids.toString());
        new FileUtils();
        FileUtils.isOSlinux();
        String basePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() ;
        try {
            basePath = URLDecoder.decode(basePath, "UTF-8");
            basePath = basePath.substring(0, basePath.indexOf('/', basePath.indexOf('/', basePath.indexOf('/') + 1) + 1))+ "/temp/cadrefiles/" + SecurityUtils.getUserId();
            System.out.println("测试服务器地址目录，打印当前取到的数据来源，basePath:" + basePath);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        File baseDir = new File(basePath);
        if (!baseDir.exists()) {
            baseDir.mkdirs();
        }
        System.out.println("basePath1:" + basePath);
        if (file.getOriginalFilename().contains("lrm")) {
            try {
                new XMLUtils();
                File comonfile = new File(basePath + ("lrmx_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + XMLUtils.randomHexString(5) + ".lrmx"));
                try {
                    file.transferTo(comonfile);
                } catch (Exception e2) {
                    System.out.println("UploadLrmxFile error:" + e2.getMessage());
                }
                return saveA01ByLrmxFile(comonfile, basePath, ids);
            } catch (Exception e3) {
                return R.error(file.getName() + ":上传失败");
            }
        } else if (!file.getOriginalFilename().contains("zip")) {
            return R.ok("操作完毕");
        } else {
            new XMLUtils();
            String zipBasePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "/temp/cadrefiles/" + SecurityUtils.getUserId() + "/" + XMLUtils.randomHexString(5) + "/";
            try {
                zipBasePath = URLDecoder.decode(zipBasePath, "UTF-8");
            } catch (UnsupportedEncodingException e4) {
                e4.printStackTrace();
            }
            File tempDir = new File(zipBasePath);
            if (!tempDir.exists()) {
                tempDir.mkdirs();
            }
            File tempfile = transferToFile(file);
            try {
                ZipUtil.zipUncompress(tempfile.getPath(), zipBasePath);
                tempfile.deleteOnExit();
                File[] fs = tempDir.listFiles();
                for (File f : fs) {
                    if (!f.isDirectory()) {
                        System.out.println(f);
                        try {
                            System.out.println("解压缩:" + zipBasePath + f.getName());
                            saveA01ByLrmxFile(new File(zipBasePath + f.getName()), zipBasePath, ids);
                        } catch (Exception e5) {
                        }
                    }
                }
                return R.error(file.getName() + ":成功");
            } catch (Exception e6) {
                return R.error(file.getName() + ":上传失败");
            }
        }
    }

    public static void deleteFile(File file) {
        if (file == null || !file.exists()) {
            flag = 0;
            System.out.println("文件删除失败,请检查文件路径是否正确");
            return;
        }
        File[] files = file.listFiles();
        for (File f : files) {
            System.out.println(file.getName());
            if (f.isDirectory()) {
                deleteFile(f);
            } else {
                f.delete();
            }
        }
    }

    private File transferToFile(MultipartFile multipartFile) {
        File file = null;
        try {
            String[] filename = multipartFile.getOriginalFilename().split("\\.");
            file = File.createTempFile(filename[0], "." + filename[1]);
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    private R saveA01ByLrmxFile(File comonfile, String basePath, String[] ids) throws IOException {
        String s;
        new XMLUtils();
        new A01();
        try {
            A01 a01 = XMLUtils.getA01ByLrmxFile(comonfile);
            a01.setA0181("在职干部");
            comonfile.delete();
            if (Integer.valueOf(this.a01Service.checkA01Repeat(a01)).intValue() > 0) {
                a01.setRepeatFlag(1);
                comonfile.deleteOnExit();
                return R.error(a01.getA0101() + "已存在！");
            }
            a01.setRepeatFlag(0);
            String a0171string = a01.getA0171string();
            if (!StringUtils.isEmpty(a0171string)) {
                a01.setA0171(Base64.decodeBase64(a0171string.replace("zhaopian str:", "")));
            } else {
                String a0105 = a01.getA0105();
                if (!StringUtils.isEmpty(a0105)) {
                    if ("女".equals(a0105)) {
                        s = RealUrlUtil.getRootUrl() + "\\cadre-system\\src\\resources\\pic\\nv_pic.jpg";
                    } else {
                        s = RealUrlUtil.getRootUrl() + "\\cadre-system\\src\\resources\\pic\\nan_pic.jpg";
                    }
                    File file = new File(s);
                    if (file.exists()) {
                        a01.setA0171(file2Byte(file));
                    }
                }
            }
            this.a01Service.getBaseMapper().insert(a01);
            List<A16> a16List = a01.getA16List();
            if (CollectionUtils.isNotEmpty(a16List)) {
                this.a16Service.saveBatch(a16List);
            }
            try {
                List<A04> a04List = a01.getA04List();
                if (!org.springframework.util.CollectionUtils.isEmpty(a04List)) {
                    this.a04Service.insertBatchSimple(a04List);
                }
                this.a04Controller.updateA01_3(a04List, a01.getFlowid());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            try {
                this.a79Service.insertBatchSimple(a01.getA79List());
            } catch (Exception e) {
            }
            for (int i19 = 0; i19 < a01.getA19List().size(); i19++) {
                try {
                    a01.getA19List().get(i19).setFlowid(a01.getA19List().get(i19).getFlowid().replace("-", ""));
                    a01.getA19List().get(i19).setA1956((short) 999);
                } catch (Exception ex2) {
                    ex2.printStackTrace();
                }
            }
            try {
                A26 a26Entity = new A26();
                a26Entity.setFlowid(GenerateUUID.getUUID());
                a26Entity.setPersonid(a01.getFlowid());
                a26Entity.setA2601(a01.getA2601());
                a26Entity.setSerial((short) 1);
                a26Entity.setIsout((short) 1);
                a26Entity.setFlag((short) 1);
                this.a26Service.insertSelective(a26Entity);
            } catch (Exception e2) {
            }
            for (String unitid : ids) {
                A19 a19 = new A19();
                B01 b01 = this.b01Service.selectById(unitid);
                a19.setFlowid(GenerateUUID.getUUID());
                a19.setPersonid(a01.getFlowid());
                a19.setA1916(b01.getB0101());
                a19.setA1915(unitid);
                a19.setA1935((short) 1);
                a19.setSort((short) 99);
                a19.setSerial((short) 99);
                this.a19Service.saveA19(a19);
                comonfile.deleteOnExit();
            }
            try {
                this.client.index(new IndexRequest(ESUtil.a01Index).id(a01.getFlowid()).source(JSON.toJSONString(a01), XContentType.JSON), RequestOptions.DEFAULT);
            }catch (Exception e3) {
                e3.printStackTrace();
            }
            return R.ok();
        } catch (Exception ex3) {
            ex3.printStackTrace();
            comonfile.delete();
            return R.error();
        }
    }

    public static byte[] file2Byte(File filePath) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(filePath);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            while (true) {
                int n = fis.read(b);
                if (n == -1) {
                    break;
                }
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        return buffer;
    }

    @PostMapping({"/uploadLrmxFiles"})
    @ApiOperation(value = "上传多个lrmx文件", notes = "file:单文件,返回结果:a01List")
    public R uploadLrmxFile(@RequestParam("file") MultipartFile[] files, HttpServletRequest request, HttpServletResponse response) throws DocumentException {
        String basePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "/temp/";
        File baseDir = new File(basePath);
        if (!baseDir.exists()) {
            baseDir.mkdirs();
        }
        new XMLUtils();
        List<A01> a01List = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        for (MultipartFile file : files) {
            File comonfile = new File(basePath + "/" + ("lrmx_" + sdf.format(new Date()) + ".lrmx"));
            try {
                file.transferTo(comonfile);
            } catch (Exception e) {
                System.out.println("UploadLrmxFile error:" + e.getMessage());
            }
            a01List.add(XMLUtils.getA01ByLrmxFile(comonfile));
            try {
                comonfile.delete();
                System.out.println("是否存在：" + comonfile.exists());
            } catch (Exception e2) {
            }
        }
        return R.ok().put("a01List", (Object) a01List);
    }

    @PostMapping({"/saveList"})
    @ApiOperation(value = "新增A01List", notes = "a01List:a01 JSON数据；")
    public R saveList(@RequestBody JSONObject json) throws IOException {
        A01 a01 = new A01();
        JSONArray a01Array = json.getJSONArray("a01List");
        new JSONArray();
        new JSONArray();
        new JSONArray();
        new JSONArray();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int a3 = 0; a3 < a01Array.size(); a3++) {
            JSONObject obj3 = (JSONObject) a01Array.get(a3);
            String name = obj3.get("a0101").toString();
            String sex = obj3.get("a0105").toString();
            String sfz = obj3.get("a0107").toString();
            try {
                String birth = obj3.get("a0106").toString().replace(".", "-") + "-01 10:00:00";
                a01 = new A01();
                a01.setA0101(name);
                a01.setA0105(sex);
                a01.setA0106(sdf.parse(birth));
                a01.setA0107(sfz);
            } catch (Exception e) {
            }
            if (Integer.valueOf(this.a01Service.checkA01Repeat(a01)).intValue() > 0) {
                return R.error("已存在姓名 性别 出生年月相同的数据！");
            }
            continue;
        }
        for (int a = 0; a < a01Array.size(); a++) {
            JSONObject obj = (JSONObject) a01Array.get(a);
            try {
                obj.put("a0106", obj.get("a0106").toString().replace(".", "-") + "-01 10:00:00");
            } catch (Exception e2) {
            }
            try {
                obj.put("a0184", obj.get("a0184").toString().replace(".", "-") + "-01 10:00:00");
            } catch (Exception e3) {
            }
            try {
                obj.put("a0138", obj.get("a0138").toString().replace(".", "-") + "-01 10:00:00");
            } catch (Exception e4) {
            }
            JSONArray a79Array = obj.getJSONArray("a79List");
            for (int a1 = 0; a1 < a79Array.size(); a1++) {
                try {
                    JSONObject obj1 = (JSONObject) a79Array.get(a1);
                    obj1.put("a7922", obj1.get("a7922").toString().replace(".", "-") + "-01 10:00:00");
                } catch (Exception e5) {
                }
            }
            obj.getJSONArray("a04List");
            JSONArray a19Array = obj.getJSONArray("a19List");
            for (int a2 = 0; a2 < a19Array.size(); a2++) {
                JSONObject obj2 = (JSONObject) a19Array.get(a2);
                try {
                    String startdate = obj2.get("a1905").toString();
                    if (!(startdate == "" || startdate == null)) {
                        startdate = startdate.replace(".", "-") + "-01 10:00:00";
                    }
                    obj2.put("a1905", startdate);
                } catch (Exception e6) {
                }
                try {
                    String enddate = obj2.get("a1910").toString();
                    if (!(enddate == "" || enddate == null)) {
                        enddate = enddate.replace(".", "-") + "-01 10:00:00";
                    }
                    obj2.put("a1910", enddate);
                } catch (Exception e7) {
                }
            }
        }
        for (A01 a012 : JSONObject.parseArray(JSONArray.toJSONString(a01Array), A01.class)) {
            a012.setA0171(Base64.decodeBase64(a012.getA0171string().replace("zhaopian str:", "")));
            this.a01Service.insertSelective(a012);
            this.a01Service.updateA0171(a012.getA0171string(), a012.getFlowid());
            try {
                this.a79Service.insertBatchSimple(a012.getA79List());
            } catch (Exception e8) {
            }
            try {
                this.a04Service.insertBatchSimple(a012.getA04List());
                this.a04Service.updateCodeIfnull();
                this.a04Controller.updateA01_3(a012.getA04List(), a012.getFlowid());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            try {
                this.a16Service.saveBatch(a012.getA16List());
            } catch (Exception ex2) {
                ex2.printStackTrace();
            }
            for (int i19 = 0; i19 < a012.getA19List().size(); i19++) {
                try {
                    a012.getA19List().get(i19).setFlowid(a012.getA19List().get(i19).getFlowid().replace("-", ""));
                    a012.getA19List().get(i19).setA1956((short) 999);
                } catch (Exception ex3) {
                    ex3.printStackTrace();
                }
            }
            this.a19Service.saveA19ByList(a012.getA19List());
            try {
                A26 a26Entity = new A26();
                a26Entity.setFlowid(GenerateUUID.getUUID());
                a26Entity.setPersonid(a012.getFlowid());
                a26Entity.setA2601(a012.getA2601());
                a26Entity.setSerial((short) 1);
                a26Entity.setIsout((short) 1);
                a26Entity.setFlag((short) 1);
                this.a26Service.insertSelective(a26Entity);
            } catch (Exception e9) {
            }
            this.client.index(new IndexRequest(ESUtil.a01Index).id(a012.getFlowid()).source(JSON.toJSONString(a012), XContentType.JSON), RequestOptions.DEFAULT);
        }
        return R.ok();
    }

    @PostMapping({"/update"})
    @A01Tag("更新")
    @SysLog(value = "修改人员基本信息", target = "A01", set = "A01", type = 1)
    @ApiOperation("改")
    public R update(@RequestBody A01 a01) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.MONTG_DATE_FORMAT);
        long startTime = System.currentTimeMillis();
        if (a01.getA0101() == null || a01.getA0106() == null || a01.getA0105() == null) {
            this.a01Service.updateByPrimaryKeySelective(a01);
            System.out.println(">>>>>>>>>A01保存完成,总共耗时" + (System.currentTimeMillis() - startTime) + "ms。");
            return R.ok();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("notflowid", a01.getFlowid());
        map.put("a0101", a01.getA0101());
        map.put("a0106", sdf.format(a01.getA0106()));
        map.put("a0105", a01.getA0105());
        map.put("a0107", a01.getA0107());
        List<A01> list = this.a01Service.getSamePerson(map);
        if ((list == null || list.size() == 0)) {
            a01.setA0102(PinYinUtil.getPingYin(a01.getA0101()).toUpperCase() + "," + PinYinUtil.getFirstSpell(a01.getA0101()).toUpperCase());
            this.a01Service.updateByPrimaryKeySelective(a01);
            System.out.println(">>>>>>>>>A01保存完成,总共耗时" + (System.currentTimeMillis() - startTime) + "ms。");
            GetResponse response = this.client.get(new GetRequest(ESUtil.a01Index, a01.getFlowid()), RequestOptions.DEFAULT);
            System.out.println(response.getSource());
            Map<String, Object> source = response.getSource();
            if (source != null) {
                A01 a01s = ESUtil.useObjectMapper(source);
                a01.setA79List(a01s.getA79List());
                a01.setA19List(a01s.getA19List());
                a01.setA04List(a01s.getA04List());
                a01.setA16List(a01s.getA16List());
                a01.setA22List(a01s.getA22List());
                a01.setA26List(a01s.getA26List());
                a01.setA17List(a01s.getA17List());
                a01.setA92List(a01s.getA92List());
                a01.setA91List(a01s.getA91List());
                this.client.index(new IndexRequest(ESUtil.a01Index).id(a01.getFlowid()).source(JSON.toJSONString(a01), XContentType.JSON), RequestOptions.DEFAULT);
            }
            return R.ok();
        }
        System.out.println(">>>>>>>>>A01数据重复");
        return R.error("干部信息重复！");
    }

    @PostMapping({"/updatephoto"})
    @SysLog(value = "修改人员头像基本信息", target = "A01", set = "A01", type = 1)
    @ApiOperation("改")
    public R updatePhoto(@RequestBody A01 a01) {
        this.a01Service.updateById(a01);
        return R.ok();
    }

    @PostMapping({"/edits"})
    @SysLog(value = "修改人员基本信息", target = "A01", set = "A01", type = 1)
    public R edits(@RequestBody A01 a01) {
        a01.setA0177b(StringEscapeUtils.unescapeHtml4(a01.getA0177b()));
        this.a01Service.updateById(a01);
        return R.ok();
    }

    @PostMapping({"/editGZDW"})
    public R editGZDW(@RequestBody A01 a01) {
        A01 record = this.a01Service.selectByPrimaryKey(a01.getFlowid());
        record.setA0183(a01.getA0183());
        this.a01Service.updateByPrimaryKeySelective(record);
        return R.ok();
    }

    @PostMapping({"/editSXLY"})
    public R editSXLY(@RequestBody A01 a01) {
        A01 record = this.a01Service.selectByPrimaryKey(a01.getFlowid());
        record.setA0176(a01.getA0176());
        this.a01Service.updateByPrimaryKeySelective(record);
        return R.ok();
    }

    @PostMapping({"/editZYJL"})
    public R editZYJL(@RequestBody A01 a01) {
        A01 record = this.a01Service.selectByPrimaryKey(a01.getFlowid());
        record.setA0177a(a01.getA0177a());
        this.a01Service.updateByPrimaryKeySelective(record);
        return R.ok();
    }

    @PostMapping({"/editUpdate"})
    @A01Tag("更新")
    @SysLog(value = "修改人员基本信息", target = "A01", set = "A01", type = 1)
    @ApiOperation("改")
    public R editUpdate(@RequestBody A01 a01) {
        this.a01Service.updateByPrimaryKeySelective(a01);
        A01 a01old = (A01) this.a01Service.getBaseMapper().selectById(a01.getFlowid());
        String temp = "";
        if (a01old.getA2602() != null) {
            temp = a01old.getA2602();
            if (a01old.getA2603() != null) {
                temp = temp + ";" + a01old.getA2603();
            }
        }
        a01.setA2601(temp);
        this.a01Service.updateByPrimaryKeySelective(a01);
        return R.ok();
    }

    @PostMapping({"/deletes"})
    @SysLog(value = "删除人员基本信息", target = "A01", set = "A01", type = DateUtil.SUB_MONTH)
    @ApiOperation("删除")
    public R deletes(@RequestBody String[] flowids) {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        if (SecurityUtils.getUserId().longValue() != 1) {
            String result = "1";
            int i = 0;
            while (true) {
                if (i >= flowids.length) {
                    break;
                } else if (this.a19Service.checkAuthByPersonid(SecurityUtils.getUserId().toString(), flowids[i]).equals("0")) {
                    result = "0";
                    break;
                } else {
                    i++;
                }
            }
            if (!result.equals("1")) {
                return R.error("选中数据存在非主管权限数据，终止删除！");
            }
        }
        for (String flowid : flowids) {
            this.a01Service.deleteByPrimaryKey(flowid);
        }
        return R.ok("删除成功");
    }

    @PostMapping({"/delete"})
    @A01Tag("删除")
    @SysLog(value = "删除人员基本信息", target = "A01", set = "A01", type = DateUtil.SUB_MONTH)
    public R delete(@RequestBody String[] flowids) throws IOException {
        deleteData("A01", flowids);
        deleteData("A19", flowids);
        deleteData("A04", flowids);
        deleteData("A79", flowids);
        deleteData("A22", flowids);
        deleteData("A16", flowids);
        for (String id : flowids) {
            try {
                DeleteRequest request = new DeleteRequest();
                request.index(ESUtil.a01Index).id(id);
                this.client.delete(request, RequestOptions.DEFAULT);
            }catch (Exception e){
                System.out.println("delete error:" + e.getMessage());
            }
        }
        return R.ok("删除成功");
    }

    public int deleteData(String tableName, String[] id) {
        List<String> idList = Arrays.asList(id);
        if ("A01".equals(tableName)) {
            for (String flowid : id) {
                if (!hasDelePerms(flowid)) {
                    throw new CadreException(ResultEnum.PERSMISS_ERROR);
                }
            }
            this.a01Service.getBaseMapper().deleteBatchIds(idList);
            return 1;
        }
        this.a19Service.deleteBatchPersonid(tableName, idList);
        return 1;
    }

    @PostMapping({"/updateOrder"})
    @ApiOperation(value = "人员批量排序", notes = "personids:人员列表，unitid:单位ID")
    public R updateOrder(@RequestBody JSONObject json) {
        JSONArray personids = json.getJSONArray("personids");
        String unitid = json.get("unitid").toString();
        this.a19Service.updateOrderByPersonArray(JSONObject.parseArray(JSONArray.toJSONString(personids), String.class), unitid);
        return R.ok("排序更新完毕");
    }

    @RequestMapping(value = {"/modifylist"}, method = {RequestMethod.POST})
    @ApiOperation(value = "人员修改记录列表", notes = "参数map->flowid:人员ID；username：用户名；startdate:开始时间；enddate：结束时间；tablename:信息集。返回值:page")
    public R modifylist(@RequestParam Map<String, Object> map) {
        return R.ok().put("page", (Object) this.sysLogService.selectList(map));
    }

    /* JADX WARN: Multi-variable type inference failed */
    /* JADX DEBUG: Type inference failed for r0v23. Raw type applied. Possible types: java.util.Map<java.lang.String, java.lang.Object> */
    @RequestMapping(value = {"/modifydiff"}, method = {RequestMethod.POST})
    @ApiOperation(value = "人员修改记录列表", notes = "参数map->id:人员ID;返回值:data")
    public R modifydiff(@RequestBody Map<String, Object> map) {
        SysLogEntity sysLog = (SysLogEntity) this.sysLogService.getBaseMapper().selectById(Long.valueOf(Long.parseLong(map.get("id").toString())));
        if (!sysLog.getOperationtable().equals("A01")) {
            Map<String, Object> maps = new HashMap<>();
            maps.put("before", sysLog.getOldparams());
            maps.put("after", sysLog.getParams());
            return R.ok().put("data", (Object) maps);
        }
        List<Map<String, Object>> map_cl = this.sysLogService.getColumnInfo(sysLog.getOperationset());
        Map<String, Object> map_r = new HashMap<>();
        if (sysLog.getOperationtype() == 2) {
            new JSONCompareUtil(map_cl);
            JSONObject json1 = new JSONObject();
            JSONObject json2 = new JSONObject();
            try {
                json2 = JSONObject.parseObject(sysLog.getOldparams() == null ? "" : sysLog.getOldparams());
            } catch (Exception e) {
            }
            Map<String, Object> map_r_t = JSONCompareUtil.compareJson(json2, json1, (String) null);
            map_r.put("after", map_r_t.get("before").toString());
            map_r.put("before", map_r_t.get("after").toString());
        } else {
            new JSONCompareUtil(map_cl);
            JSONObject json12 = new JSONObject();
            try {
                json12 = JSONObject.parseObject(sysLog.getParams() == null ? "" : sysLog.getParams());
            } catch (Exception e2) {
            }
            JSONObject json22 = new JSONObject();
            try {
                json22 = JSONObject.parseObject(sysLog.getOldparams() == null ? "" : sysLog.getOldparams());
            } catch (Exception e3) {
            }
            map_r = JSONCompareUtil.compareJson(json12, json22, (String) null);
        }
        return R.ok().put("data", (Object) map_r);
    }

    /*  JADX ERROR: JadxRuntimeException in pass: BlockProcessor
        jadx.core.utils.exceptions.JadxRuntimeException: Unreachable block: B:18:0x019f
        	at jadx.core.dex.visitors.blocks.BlockProcessor.checkForUnreachableBlocks(BlockProcessor.java:86)
        	at jadx.core.dex.visitors.blocks.BlockProcessor.processBlocksTree(BlockProcessor.java:52)
        	at jadx.core.dex.visitors.blocks.BlockProcessor.visit(BlockProcessor.java:44)
        */
    @RequestMapping(value = {"/exportCadreFiles"}, method = {RequestMethod.POST})
    @ApiOperation(value = "导出人事信息", notes = "根据单位生成目录，最终导出压缩文件")
    public R exportCadreFiles(HttpServletResponse r7) {
        /*
        // Method dump skipped, instructions count: 682
        */
        throw new UnsupportedOperationException("Method not decompiled: com.tdqy.cadre.modular.profess.controller.A01Controller.exportCadreFiles(javax.servlet.http.HttpServletResponse):com.tdqy.cadre.core.utils.R");
    }

    @RequestMapping(value = {"/downloadCadreFiles"}, method = {RequestMethod.POST})
    @ApiOperation("下载人事信息")
    private void toDownloadFile(HttpServletResponse httpServletResponse) {
        String basePath;
        new FileUtils();
        if (FileUtils.isOSlinux()) {
            basePath = "/tmp/cadrelrmxfiles/" + SecurityUtils.getUserId() + "/";
        } else {
            File[] roots = File.listRoots();
            if (roots.length > 1) {
                basePath = roots[1] + "cadrefiles\\" + SecurityUtils.getUserId() + "\\";
            } else {
                basePath = roots[0] + "cadrefiles\\" + SecurityUtils.getUserId() + "\\";
            }
        }
        WordUtils.toDownload(new File(basePath + "干部人事信息[" + new SimpleDateFormat("yyyy.MM.dd").format(new Date()) + "].zip"), httpServletResponse);
    }

    private List<File> getWookbooksAndFileList(List<Map<String, Object>> a01List, String temp_path, String templetPath) {
        String a01_a0141;
        String zzmm;
        List<File> fileList = new ArrayList<>();
        for (Map<String, Object> map : a01List) {
            try {
                String a01_a0101 = map.get("a01_a0101") == null ? "" : String.valueOf(map.get("a01_a0101"));
                String a01_a0104 = map.get("a01_a0104") == null ? "" : String.valueOf(map.get("a01_a0104"));
                String a01_a0107_time = map.get("a01_a0107_time") == null ? "" : String.valueOf(map.get("a01_a0107_time"));
                String a01_a0117 = map.get("a01_a0117") == null ? "" : String.valueOf(map.get("a01_a0117"));
                String a01_a0111 = map.get("a01_a0111") == null ? "" : String.valueOf(map.get("a01_a0111"));
                String a01_a0114 = map.get("a01_a0114") == null ? "" : String.valueOf(map.get("a01_a0114"));
                String a01_a0185 = map.get("a01_a0185") == null ? "" : String.valueOf(map.get("a01_a0185"));
                String a01_sfz = map.get("a01_sfz") == null ? "" : String.valueOf(map.get("a01_sfz"));
                String a01_a0134_time = map.get("a01_a0134_time") == null ? "" : String.valueOf(map.get("a01_a0134_time"));
                String valueOf = map.get("a01_a0141") == null ? "" : String.valueOf(map.get("a01_a0141"));
                String a01_a0184a = map.get("a01_a0184a") == null ? "" : String.valueOf(map.get("a01_a0184a"));
                if (a01_a0184a == null || a01_a0184a.equals("")) {
                    zzmm = "";
                    a01_a0141 = "";
                } else if (Pattern.compile("^\\d+(\\.\\d+)?$").matcher(a01_a0184a.trim()).matches()) {
                    zzmm = "中共党员";
                    a01_a0141 = map.get("a01_a0141") == null ? "" : String.valueOf(map.get("a01_a0141"));
                } else {
                    int count = 0;
                    List<String> timesList = new ArrayList<>();
                    Matcher matcher = Pattern.compile("\\d+(\\.\\d+)?").matcher(a01_a0184a.trim());
                    while (matcher.find()) {
                        count++;
                        timesList.add(matcher.group());
                    }
                    if (count != 0) {
                        for (int z = 0; z < timesList.size(); z++) {
                            a01_a0184a = a01_a0184a.trim().replace(timesList.get(z), "中共党员");
                        }
                        zzmm = a01_a0184a;
                        a01_a0141 = map.get("a01_a0141") == null ? "" : String.valueOf(map.get("a01_a0141"));
                    } else if (a01_a0184a.contains("中共") || a01_a0184a.contains("预备党员")) {
                        zzmm = a01_a0184a;
                        a01_a0141 = map.get("a01_a0141") == null ? "" : String.valueOf(map.get("a01_a0141"));
                    } else {
                        zzmm = a01_a0184a;
                        a01_a0141 = "";
                    }
                }
                System.out.println("政治面貌：" + zzmm + ",入党时间：" + a01_a0141);
                String a01_a0902 = map.get("a01_a0902") == null ? "" : String.valueOf(map.get("a01_a0902"));
                String a01_a0905 = map.get("a01_a0905") == null ? "" : String.valueOf(map.get("a01_a0905"));
                String a01_a0814 = map.get("a01_a0814") == null ? "" : String.valueOf(map.get("a01_a0814"));
                String a01_a0801 = map.get("a01_a0801") == null ? "" : String.valueOf(map.get("a01_a0801"));
                String a01_a0901 = map.get("a01_a0901") == null ? "" : String.valueOf(map.get("a01_a0901"));
                String a01_a0903 = map.get("a01_a0903") == null ? "" : String.valueOf(map.get("a01_a0903"));
                String new1002 = map.get("new1002") == null ? "" : String.valueOf(map.get("new1002"));
                Blob b = map.get("a1701") == null ? null : (Blob) map.get("a1701");
                Workbook wb = PoiUtil.createWorkbook(templetPath);
                Sheet sheet = wb.getSheetAt(0);
                Row row = sheet.getRow(1);
                row.getCell(2).setCellValue(a01_a0101);
                row.getCell(6).setCellValue(a01_a0104);
                row.getCell(10).setCellValue(a01_a0107_time);
                if (b != null) {
                    byte[] bs = b.getBytes(1, (int) b.length());
                    XSSFDrawing patriarch = (XSSFDrawing) sheet.createDrawingPatriarch();
                    XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 12, 1, 15, 5);
                    anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
                    patriarch.createPicture(anchor, wb.addPicture(bs, 5));
                }
                Row row2 = sheet.getRow(2);
                row2.getCell(2).setCellValue(a01_a0117);
                row2.getCell(6).setCellValue(a01_a0111);
                row2.getCell(10).setCellValue(a01_a0114);
                Row row3 = sheet.getRow(3);
                row3.getCell(2).setCellValue(a01_a0134_time);
                row3.getCell(6).setCellValue(zzmm);
                row3.getCell(10).setCellValue(a01_a0141);
                sheet.getRow(4).getCell(2).setCellValue(new1002);
                Row row4 = sheet.getRow(5);
                row4.getCell(2).setCellValue(a01_a0185);
                row4.getCell(6).setCellValue(a01_sfz);
                Row row5 = sheet.getRow(6);
                row5.getCell(4).setCellValue(a01_a0902);
                row5.getCell(10).setCellValue(a01_a0814);
                Row row6 = sheet.getRow(7);
                row6.getCell(4).setCellValue(a01_a0905);
                row6.getCell(10).setCellValue("");
                Row row7 = sheet.getRow(8);
                row7.getCell(4).setCellValue(a01_a0801);
                row7.getCell(10).setCellValue(a01_a0903);
                Row row8 = sheet.getRow(9);
                row8.getCell(4).setCellValue(a01_a0901);
                row8.getCell(10).setCellValue("");
                PoiUtil.writeExcel(wb, temp_path + "\\" + a01_a0101 + ".xlsx");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return fileList;
    }

    private void setWorkbook(List<A01> a01List, String temp_path) {
        Workbook wb = PoiUtil.createWorkbook("/xls/干部人事信息.xlsx");
        wb.getSheetAt(0);
        PoiUtil.writeExcel(wb, temp_path + "干部人事信息.xlsx");
    }

    @GetMapping({"/record/{flowId}"})
    @ApiOperation("电子档案数据")
    public R record(@PathVariable("flowId") String flowId) throws NoSuchAlgorithmException, Exception {
        A01 a01 = (A01) this.a01Service.getBaseMapper().selectById(flowId);
        try {
            SecurityUtils.getUsername();
        } catch (Exception e) {
        }
        String A0184 = a01.getA0107() == null ? "" : a01.getA0107();
        String A0184des = "";
        String pkey = a01.getA0107() == null ? "" : a01.getA0107();
        new Md5EncodeUtil();
        new DesUtilNet();
        try {
            pkey = DesUtilNet.GetBase64Str(DesUtilNet.encrypt(Md5EncodeUtil.md5EncodeNew(Md5EncodeUtil.md5EncodeNew(pkey))));
        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }
        String usergdname = "";
        String csny = "";
        if (a01.getA0107() == null || a01.getA0107().equals("")) {
            A0184des = "";
        } else {
            try {
                A0184des = DesUtilNet.GetBase64Str(DesUtilNet.encrypt(A0184));
            } catch (Exception e3) {
                e3.printStackTrace();
            }
        }
        if (a01.getA0106() != null) {
            try {
                csny = DesUtilNet.GetBase64Str(DesUtilNet.encrypt(new SimpleDateFormat("yyyyMM").format(a01.getA0106())));
            } catch (Exception e4) {
                e4.printStackTrace();
            }
        } else {
            csny = "";
        }
        if (a01.getA0101() == null || a01.getA0101().equals("")) {
            usergdname = "";
        } else {
            try {
                usergdname = DesUtilNet.GetBase64Str(DesUtilNet.encrypt(a01.getA0101()));
            } catch (Exception e5) {
                e5.printStackTrace();
            }
        }
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        String ipAddr = IPUtils.getIpAddr(request);
        if (ipAddr.equals("0:0:0:0:0:0:0:1")) {
            ipAddr = "127.0.0.1";
        }
        String ipAddrJM = "";
        try {
            ipAddrJM = DesUtilNet.GetBase64Str(DesUtilNet.encrypt(ipAddr));
        } catch (Exception e6) {
            e6.printStackTrace();
        }
        System.out.println("===========> login ipaddress:" + IPUtils.getIpAddr(request));
        String macAddr = "";
        try {
            macAddr = CookiesUtil.getCookieByName(request, "mac-addr-orginal").getValue();
        } catch (Exception e7) {
        }
        System.out.println("===========> login macaddress:" + macAddr);
        new StringBuffer();
        String macAddr2 = macAddr.replace(":", "-");
        String macAddrJM = "";
        try {
            macAddrJM = DesUtilNet.GetBase64Str(DesUtilNet.encrypt(macAddr2));
        } catch (Exception e8) {
            e8.printStackTrace();
        }
        String str = this.recordsystemurl;
        return R.ok("读取档案").put("url", (Object) this.recordsystemurl).put("userid", (Object) "fghqj6Nu8Ws=").put("userinfo", (Object) "").put("A0184", (Object) A0184des).put("sort", (Object) "ZNxNsMPMR7U=").put("pkey", (Object) pkey).put("usergdname", (Object) usergdname).put("csny", (Object) csny).put("ip", (Object) ipAddrJM).put("mac", (Object) macAddrJM).put("mac-test", (Object) macAddr2).put("ip-test", (Object) ipAddr);
    }

    private boolean hasDelePerms(String flowid) {
        Long userId = SecurityUtils.getUserId();
        if (userId.longValue() == 1) {
            return true;
        }
        return this.a01Service.queryHasUnitIds(userId).contains(this.a01Service.queryUnitId(flowid));
    }

    @RequestMapping({"/infoLog"})
    public R infoLog(String flowid) {
        return R.ok().put("data", (Object) ((SysLogEntity) this.sysLogService.getBaseMapper().selectById(flowid)));
    }

    @GetMapping({"/calculateRetirementDate"})
    @ApiOperation("计算退休年龄")
    public String calculateRetirementDate(@RequestParam(value ="birthDateString")String birthDateString,@RequestParam(value ="gender") String gender,@RequestParam(value ="isLeader") boolean isLeader) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM");
        Date birthDate;
        try {
            birthDate = dateFormat.parse(birthDateString);
        } catch (ParseException e) {
            throw new RRException("该员工已超过退休年龄 " + birthDateString);
        }
        // 判断出生日期。男性1965.女性1970年之前的返回错误信息：该员工已超过退休年龄
        if (gender.equalsIgnoreCase("male") && birthDate.getYear()+1900 < 1965) {
            throw new RRException("该员工已超过退休年龄 " + birthDateString);
        }
        if (gender.equalsIgnoreCase("female") && birthDate.getYear()+1900 < 1970) {
            throw new RRException("该员工已超过退休年龄" + birthDateString);
        }
        int birthYear = birthDate.getYear() + 1900;
        int birthMonth = birthDate.getMonth() + 1;

        int baseAge = 0;
        int startYear = 0;
        int endYear = 0;

        if ("male".equalsIgnoreCase(gender)) {
            // 男性
            baseAge = 60;
            startYear = 1965;
            endYear = 1976;
        } else if ("female".equalsIgnoreCase(gender)) {
            // 女性
            if (isLeader) {
                // 女领导统一认定为60周岁退休
                baseAge = 60;
                startYear = 1970;
                endYear = 1981;
            } else {
                // 普通女职工
                baseAge = 55;
                startYear = 1970;
                endYear = 1981;
            }
        } else {
            throw new IllegalArgumentException("Invalid gender: " + gender);
        }

        // 计算延迟月数
        int delayMonths = (int) Math.ceil(((birthYear - startYear) * 12 + (birthMonth - 1)) / 4.0);

        // 计算延长的年限和多余的月数
        int extendedYears = delayMonths / 12;
        int extraMonths = delayMonths % 12;

        // 计算退休年份和月份
        int retirementYear = birthYear + baseAge + extendedYears;
        int retirementMonth = birthMonth + extraMonths;

        // 如果月份超过12，则进位到下一年
        if (retirementMonth > 12) {
            retirementYear += (retirementMonth - 1) / 12;
            retirementMonth = (retirementMonth - 1) % 12 + 1;
        }

        // 设置退休年龄上限
        if ("male".equalsIgnoreCase(gender) && birthYear >= 1976) {
            baseAge = 63;
            // 重新计算退休年份和月份
            retirementYear = birthYear + baseAge;
            retirementMonth = birthMonth;
        } else if ("female".equalsIgnoreCase(gender) && birthYear >= 1981) {
            baseAge = isLeader ? 60 : 58;
            // 重新计算退休年份和月份
            retirementYear = birthYear + baseAge;
            retirementMonth = birthMonth;
        }

        // 返回退休日期（格式化为字符串）
        return dateFormat.format(new Date(retirementYear - 1900, retirementMonth - 1, 1));
    }
}
